<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/8/22 0022
 * Time: 15:38
 */

use think\Db;

/**
 * 获取唯一序列号
 * @return string
 */
function getGuid() {
    $charid = strtoupper(md5(uniqid(mt_rand(), true)));
    //$hyphen = chr(45);// "-"
    $hyphen = '';// "-"
    $uuid = substr($charid, 0, 8).$hyphen
        .substr($charid, 8, 4).$hyphen
        .substr($charid,12, 4).$hyphen
        .substr($charid,16, 4).$hyphen
        .substr($charid,20,12);
    return $uuid;
}

/**
 * 获取随机字符串
 * @return string
 */
function create_invite_code() {
    $code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $rand = $code[rand(0,25)]
        .strtoupper(dechex(date('m')))
        .date('d')
        .substr(time(),-5)
        .substr(microtime(),2,5)
        .sprintf('%02d',rand(0,99));
    for(
        $a = md5( $rand, true ),
        $s = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ',
        $d = '',
        $f = 0;
        $f < 6;
        $g = ord( $a[ $f ] ),
        $d .= $s[ ( $g ^ ord( $a[ $f + 8 ] ) ) - $g & 0x1F ],
        $f++
    );
    return $d;
}

/**
 * 通过主键获取记录内容
 * @param $id 主键
 * @param $table_name 表名
 * @param null $field 字段
 * @return array|mixed|null|PDOStatement|string|\think\Model
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function getmodel($id,$table_name,$field=null){
    $db = Db::name($table_name)->where('id',$id);

    if(is_null($field)){
        return $db->find();
    }else{
        if(strpos($field,',')===false){
            return $db->value($field);
        }else{
            return $db->field($field)->find();
        }
    }
}
if(!function_exists('time_tran')){
    /**
     * @Description: 将时间转换为几秒前、几分钟前、几小时前、几天前
     * @Author: Yang
     * @param string $the_time 需要转换的时间
     * @return string
     */
    function time_tran($the_time)
    {
        $now_time = date("Y-m-d H:i:s", time());
        $now_time = strtotime($now_time);
        $show_time = strtotime($the_time);
        $dur = $now_time - $show_time;
        if ($dur < 0) {
            return $the_time;
        } else {
            if ($dur < 60) {
                return $dur . '秒前';
            } else {
                if ($dur < 3600) {
                    return floor($dur / 60) . '分钟前';
                } else {
                    if ($dur < 86400) {
                        return floor($dur / 3600) . '小时前';
                    } else {
                        if ($dur < 259200) { // 3天内
                            return floor($dur / 86400) . '天前';
                        } else {
                            return $the_time;
                        }
                    }
                }
            }
        }
    }
}